package action.newelifile;


import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import action.pojo.LocalFilePojo;
import action.util.Tool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class SearchActivity extends Activity{
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public ProgressDialog mProgressDialog;
	public static boolean SUB = false;
	public static boolean TYPE = false;
	public boolean running = true;
	private Button search_btn;
	private Spinner directory, type_search, day_spiner, size_spiner;
	private CheckBox include_sub;
	private EditText name_search;
	long sizeFile;
	String url, search_str, directory_str, fectching_str;
	public static ArrayList<LocalFilePojo> array;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		
		initAttribute();
	}

	public void initAttribute(){
		directory = (Spinner) findViewById(R.id.directory);
		type_search = (Spinner) findViewById(R.id.type_search);
		name_search = (EditText) findViewById(R.id.name_et);
		size_spiner = (Spinner) findViewById(R.id.size_spinner);
		day_spiner = (Spinner) findViewById(R.id.day_spinner);
		include_sub = (CheckBox) findViewById(R.id.sub_cbx);
		search_btn = (Button) findViewById(R.id.serch_btn);
		array = new ArrayList<LocalFilePojo>();
		init();
	}
	public void init() {
		String[] s = {"mnt/","mnt/sdcard"};
		ArrayAdapter<String> adapter1 =
			new ArrayAdapter<String>(SearchActivity.this,
					android.R.layout.select_dialog_singlechoice, s);
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		directory.setAdapter(adapter1);
		directory.setSelection(0);
		directory.setOnItemSelectedListener(onItemDirectory());

		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
				SearchActivity.this, R.array.type_search_arr,
				android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		type_search.setAdapter(adapter2);
		type_search.setSelection(0);
		type_search.setOnItemSelectedListener(onItemTypeSearch());

		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter
		.createFromResource(SearchActivity.this, R.array.day_arr,
				android.R.layout.simple_spinner_item);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		day_spiner.setAdapter(adapter3);
		day_spiner.setSelection(0);

		ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
				SearchActivity.this, R.array.size_arr,
				android.R.layout.simple_spinner_item);
		adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		size_spiner.setAdapter(adapter4);
		size_spiner.setSelection(0);

		search_btn.setOnClickListener(onClickSearchListener());
	}

	public OnItemSelectedListener onItemDirectory() {
		OnItemSelectedListener onSelect = new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String name = parent.getItemAtPosition(position).toString();
				directory_str = name;
			}


			public void onNothingSelected(AdapterView<?> arg0) {
			}
		};
		return onSelect;
	}
	public OnItemSelectedListener onItemTypeSearch() {
		OnItemSelectedListener onSelect = new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					TYPE = false;
					System.out.println("a");
					break;
				case 1:
					TYPE = true;
					System.out.println("b");
					break;
				default:
					break;
				}
			}


			public void onNothingSelected(AdapterView<?> arg0) {
			}
		};
		return onSelect;
	}

	public OnClickListener onClickSearchListener() {
		OnClickListener onSearchClick = new OnClickListener() {

			public void onClick(View v) {
				search_str = name_search.getText().toString().trim();
				if (search_str == null || search_str.equals("")) {
					System.out.println("ABC");
					AlertDialog.Builder builder = new AlertDialog.Builder(
							SearchActivity.this);
					builder.setTitle("Missing");
					builder.setMessage("You have to type searching name");
					builder.setPositiveButton("Ok", null);
					builder.show();
					name_search.requestFocus();
				} else {
					processOptionSearch();
				}
			}
		};
		return onSearchClick;
	}
	public void processOptionSearch() {
		try {
			if (include_sub.isChecked()) {
				System.out.println("sub");
				SUB = true;
			} else {
				SUB = false;
			}
			searching();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	ArrayList<LocalFilePojo> lfolder;
	ArrayList<LocalFilePojo> lfile;
	public void searching() {
		lfolder = new ArrayList<LocalFilePojo>();
		lfile = new ArrayList<LocalFilePojo>();
		running = true;
		new AsyncTask<String, String, Void>() {


			protected void onPreExecute() {
				mProgressDialog = ProgressDialog.show(SearchActivity.this, "",
						"Loading...", true);
				mProgressDialog.setCancelable(true);
				mProgressDialog.setOnCancelListener(new OnCancelListener() {

					public void onCancel(DialogInterface dialog) {
						running = false;
					}
				});
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setMessage(progress[0]);
			}


			protected Void doInBackground(String... params) {
				if(running){
					array.clear();
					File file = new File(directory_str);
					File[] child = file.listFiles();
					if (child.length == 0) {
						return null;
					}
					LocalFilePojo files = null;
					for (int i = 0; i < child.length; i++) {
						if (!file.isHidden()) {
							if (SUB) {
								searchInSubFolder(child[i]);
							} else {
								if (!TYPE) {// search folder and file
									if (child[i].isFile()) {
										String temp = child[i].getName().toString()
										.toUpperCase();
										int index = temp.lastIndexOf(".");
										temp = temp.substring(0, index);
										if (temp.indexOf(search_str.toUpperCase()) >= 0) {
											files = new LocalFilePojo();
											files.setFileItem(file);
											lfile.add(files);
										}
									} else {
										if (child[i].getName().toString()
												.toUpperCase()
												.indexOf(search_str.toUpperCase()) >= 0) {
											files = new LocalFilePojo();
											files.setFileItem(file);
											lfolder.add(files);
										}
									}
								} else {// search extendsion file (.*)
									boolean flag = Tool.checkExtendFile(child[i]
									                                          .getName().toString().toUpperCase(),
									                                          search_str.toUpperCase());
									if (flag) {
										files = new LocalFilePojo();
										files.setFileItem(file);
										lfile.add(files);
									}
								}
							}

							fectching_str = child[i].getAbsoluteFile().toString();
							publishProgress(fectching_str);
						}
					}


				}
				return null;
			}

			public void checkDay() {
				int itemSelect = day_spiner.getSelectedItemPosition();
				int day = 0;
				switch (itemSelect) {
				case 0:
					day = 0;
					break;
				case 1:
					day = 7;
					break;
				case 2:
					day = 14;
					break;
				case 3:
					day = 21;
					break;
				case 4:
					day = 30;
					break;
				case 5:
					day = 90;
					break;
				case 6:
					day = 180;
					break;
				case 7:
					day = 270;
					break;
				case 8:
					day = 365;
					break;
				default:
					day = 0;
					break;
				}
				if (day != 0) {
					Calendar current = Calendar.getInstance();
					int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
					long result = current.getTimeInMillis() - (day*MILLIS_IN_DAY);
					LocalFilePojo files;
					for (int i = 0; i < array.size(); i++) {
						files = array.get(i);
						if (!files.getFileItem().isDirectory()) {
							if (files.getFileItem().lastModified() < result) {
								array.remove(i);
								i--;
							}
						}
					}
				}
			}

			public void checkSize() {
				String tempSize = size_spiner.getSelectedItem().toString()
				.trim();
				if (!tempSize.equals("")) {
					long size = Long.parseLong(tempSize);
					LocalFilePojo files;
					for (int i = 0; i < array.size(); i++) {
						files = array.get(i);
						if (!files.getFileItem().isDirectory()) {
							if (files.getFileItem().length() > size) {
								array.remove(i);
								i--;
							}
						}
					}
				}
			}

			public void searchInSubFolder(File file) {
				try {
					if (!file.isHidden()) {
						fectching_str = file.getAbsoluteFile().toString();
						publishProgress(fectching_str);
						LocalFilePojo files = null;
						if (file.isDirectory()) {
							if (!TYPE) {
								if (file.getName().toString().toUpperCase()
										.indexOf(search_str.toUpperCase()) >= 0) {
									files = new LocalFilePojo();
									files.setFileItem(file);
									lfolder.add(files);
								}
							}
							File[] child = file.listFiles();
							if (child == null || child.length == 0) {
								return;
							}
							for (int i = 0; i < child.length; i++) {
								fectching_str = child[i].getAbsoluteFile()
								.toString();
								publishProgress(fectching_str);
								searchInSubFolder(new File(file,
										child[i].getName()));
							}

						} else if (file.isFile()) {
							if (!TYPE) {
								String temp = file.getName().toString()
								.toUpperCase();
								int index = temp.lastIndexOf(".");
								if (index > 0) {
									temp = temp.substring(0, index);
								}
								if (temp.indexOf(search_str.toUpperCase()) >= 0) {
									files = new LocalFilePojo();
									files.setFileItem(file);
									lfile.add(files);
									fectching_str = file.getAbsoluteFile()
									.toString();
									publishProgress(fectching_str);
								}
							} else {
								boolean flag = Tool.checkExtendFile(file
										.getName().toString().toUpperCase(),
										search_str.toUpperCase());
								if (flag) {
									files = new LocalFilePojo();
									files.setFileItem(file);
									lfile.add(files);
									fectching_str = file.getAbsoluteFile()
									.toString();
									publishProgress(fectching_str);
								}
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}


			protected void onPostExecute(Void arg) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
					array.addAll(lfolder);
					array.addAll(lfile);
					if (array.size() > 0) {
						checkDay();
						checkSize();
						initListSearch();
						Intent intent = new Intent(SearchActivity.this,
								ListSearchActivity.class);
						startActivity(intent);
						finish();
					} else {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								SearchActivity.this);
						builder.setTitle("Alert");
						builder.setMessage("File not found");
						builder.setPositiveButton("Ok", null);
						builder.show();
					}
				}
			}
		}.execute("");
	}

	public void initListSearch() {
		Intent action=null;
		Drawable icon = null;
		Bitmap bitmap= null;
		for (LocalFilePojo item:array) {
			if (!item.getFileItem().isDirectory()) {
				action = new Intent(Intent.ACTION_VIEW);
				if (Tool.checkExtendFile(item.getFileItem().getName(), ".txt")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".csv")) {
					icon = getResources().getDrawable(
							R.drawable.text_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "text/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".xml")) {
					icon = getResources().getDrawable(
							R.drawable.xml_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "text/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".flv")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".3gp")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".avi")) {
					bitmap = ThumbnailUtils.createVideoThumbnail(
							item.getFileItem().getPath(), Thumbnails.MICRO_KIND);
					icon = new BitmapDrawable(bitmap);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "video/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".mp3")) {
					icon = getResources().getDrawable(
							R.drawable.mp3_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "audio/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".doc")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".docx")) {
					icon = getResources().getDrawable(
							R.drawable.word_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "text/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".ppt")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".pptx")) {
					icon = getResources().getDrawable(
							R.drawable.pptx_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "text/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".xls")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".xlsx")) {
					icon = getResources().getDrawable(
							R.drawable.xlsx_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "text/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".zip")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".rar")) {
					icon = getResources().getDrawable(
							R.drawable.rar_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "video/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".jpg")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".jpeg")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".png")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".bmp")
						|| Tool.checkExtendFile(item.getFileItem().getName(), ".gif")) {
					bitmap = BitmapFactory.decodeFile(item.getFileItem().getPath());
					icon = new BitmapDrawable(bitmap);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())), "image/*");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".apk")) {
					icon = getResources().getDrawable(
							R.drawable.apk_file);
					action.setDataAndType(Uri.fromFile(new File(item.getFileItem().getPath())),
					"application/vnd.android.package-archive");
				} else if (Tool.checkExtendFile(item.getFileItem().getName(), ".exe")) {
					icon = getResources().getDrawable(
							R.drawable.exe_file);
				} else {
					icon = getResources().getDrawable(
							R.drawable.unknown_file);
				}
				item.setIcon(icon);
				item.setAction(action);
			} else {
				icon = getResources().getDrawable(
						R.drawable.folder);
				item.setIcon(icon);
			}
		}
	}
}
